//
//  SEBaseViewController.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/2.
//

import UIKit

class SEBaseViewController: UIViewController {
    
    var navBarStyle: SENavigationBarStyle = .white
    
    var inCurrentVC: Bool { UIViewController.current?.isEqual(self) == true }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.background
        UIScrollView.appearance().contentInsetAdjustmentBehavior = .never
        
        NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
        
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setupNavBar()
    }
    
    func setupUI() {}
    
    @objc func didBecomeActive() {}

    func addEndEditingTap() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
        view.addGestureRecognizer(tap)
    }

    @objc private func tapAction() {
        view.endEditing(true)
    }

    func presentLoginViewController(selector: Selector?, handle: (() -> Void)? = nil) {

        UserTools.removeAllUserInfo()
        
        if UIViewController.current is SELoginViewController { return }
        
        let vc = SELoginViewController()
        vc.loginSuccessHandler = { success in
            if success {
                guard selector != nil else { return }
                self.perform(selector)
            }
        }
        let nav = SENavigationController(rootViewController: vc)
        nav.modalPresentationStyle = .fullScreen
        present(nav, animated: true) {
            // 弹出登录页面后不回调 不用弹出错误提示
//            handle?()
        }
    }
    
    func setupNavBar() {
        guard let nav = navigationController else { return }
        
        if nav.visibleViewController == self {
            nav.navBarStyle(.white)
            nav.disablePopGesture = false
            nav.setNavigationBarHidden(false, animated: true)
            if nav.viewControllers.count > 1 {
                navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "nav_back_black"), style: .plain, target: self, action: #selector(popBack))
            } else {
                navigationItem.leftBarButtonItem = nil
            }
        }
    }
    
    @objc func popBack() {
        navigationController?.popViewController(animated: true)
    }
}

extension SEBaseViewController {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
}
